//
//  IAPManager.m
//  IAPDemo
//
//  Created by Charles.Yao on 2016/10/31.
//  Copyright © 2016年 com.pico. All rights reserved.
//

#import "IAPManager.h"

@interface IAPManager ()

@property (nonatomic, strong) IAPHelper *iap;

@property (nonatomic, assign) BOOL goodsRequesting; //判断一次交易请求是否正在进行

@property (nonatomic, copy) IAPProductTradeResultBlock tradeResultBlock;

@end

@implementation IAPManager

static IAPManager *_instance;
+ (id)allocWithZone:(NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

+ (IAPManager *)shared
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

#pragma mark setter/getter
- (IAPHelper *)iap {
    if (!_iap) {
        _iap = [IAPHelper new];
    }
    return _iap;
}

/***
 内购支付两个阶段：
 1.app直接向苹果服务器请求商品，支付阶段；
 2.苹果服务器返回凭证，app向公司服务器发送验证，公司再向苹果服务器验证阶段；
 */

/**
 阶段一正在进行中,app退出。
 在程序启动时，设置监听，监听是否有未完成订单，有的话恢复订单。
 */

- (void)startIAPObserver
{
    @weakify(self)
    [self.iap addTransactionObserver:nil toCheckReceiptBlock:^(SKPaymentTransaction *transaction) {
        @strongify(self)
        
        [self handleCheckReceipt:transaction];
        
    } onCompletion:^(SKPaymentTransaction *transaction) {
        @strongify(self)
        
        [self handleBuyProductCompleteResponseBlock:transaction];
        
    }];
}

#pragma mark 开始请求苹果商品
- (void)requestProductWithId:(NSString *)productId
            tradeResultBlock:(IAPProductTradeResultBlock)tradeResultBlock
{
    
    self.tradeResultBlock = tradeResultBlock;
    //是否登录
    
    
    //是否一次交易请求完成
    if (self.goodsRequesting){
        NSLog(@"当前有交易正在进行中");
        [LPToast toast:@"当前有交易正在进行中"];
        return;
    }
    
    [LPToast toast:@"正在连接App Store"];
    
    //用户未允许app内购
    if (!self.iap.canMakePayments) {
        [self handleError:IAP_FILEDCOED_NORIGHT error:nil];
        return;
    }
    
    //用户允许app内购
    if (IsEmptyOrNull(productId)) {
        [self handleError:IAP_FILEDCOED_EMPTYGOODS error:nil];
        return;
    }
    
    self.goodsRequesting = YES;
    NSSet *productIdentifiers = [NSSet setWithObjects:productId, nil];
    @weakify(self)
    [self.iap requestProductsWithProductIdentifiers:productIdentifiers completion:^(SKProductsRequest* request , SKProductsResponse* response, NSError *error) {
        @strongify(self)
        
        if (error) {
            [self handleError:IAP_FILEDCOED_APPLECODE error:error.localizedDescription];
            return;
        }
        
        if (response.products.count <= 0) {
            NSLog(@"向苹果服务器请求商品信息失败");
            [self handleError:IAP_FILEDCOED_CANNOTGETINFORMATION error:nil];
            return;
        }
        
        SKProduct* product =[self.iap.products safeObjectAtIndex:0];
        [self printProduct:product];
        
        [self.iap buyProductWithSKProduct:product transactionState:^(SKPaymentTransaction *transaction) {
            
            [self handelTransactionState:transaction];
            
        } toCheckReceiptBlock:^(SKPaymentTransaction *transaction) {
            
             [self handleCheckReceipt:transaction];
            
        } onCompletion:^(SKPaymentTransaction *transaction) {
            
            [self handleBuyProductCompleteResponseBlock:transaction];
            
        }];
    }];
    
}

#pragma mark 交易状态处理
- (void)handelTransactionState:(SKPaymentTransaction *)transaction {
    switch (transaction.transactionState) {
        case SKPaymentTransactionStatePurchasing:
        {
            [LPToast toast:@"商品正在请求中"];
            break;
        }
        case SKPaymentTransactionStatePurchased: {
            break;
        }
        case SKPaymentTransactionStateRestored:{
            break;
        }
        case SKPaymentTransactionStateFailed: {
            if(transaction.error.code == SKErrorPaymentCancelled) {
                [self handleError:IAP_FILEDCOED_USERCANCEL error:nil];
                return;
            }
            [self handleError:IAP_FILEDCOED_BUYFILED error:nil];
            break;
        }
        default:
            break;
    }
}
#pragma mark 交易凭证处理
- (void)handleCheckReceipt:(SKPaymentTransaction *)transaction
{
    [LPToast toast:@"获取相关支付凭证"];
    
    [self.iap checkReceipt:[NSData dataWithContentsOfURL:NSBundle.mainBundle.appStoreReceiptURL] andSharedSecret:nil onCompletion:^(id response, NSError *error) {
        
        if ([response isKindOfClass:NSDictionary.class]) {
            
            if (SafeGetIntValue(response[@"status"]) == 0) {
                [self.iap finishTransaction:transaction];
                return;
            }
            
            [self handleError:IAP_FILEDCOED_BUYFILED error:nil];
            return;
        }
        
        NSLog(@"response:%@",response);
        [self handleError:IAP_FILEDCOED_BUYFILED error:nil];
        
    }];
        
//    [[WXYZ_NetworkRequestManger sharedManager] POST:ApplePayBack parameters:@{@"receipt":receipt} success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * _Nullable dic) {
//        if (Request_Success_From(dic)) {
//            [self requestSuccess];
//        } else {
//            [self handleError:IAP_FILEDCOED_BUYFILED error:nil];
//        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [self handleError:IAP_FILEDCOED_BUYFILED error:nil];
//    }];
    
}
#pragma mark 交易完成处理
- (void)handleBuyProductCompleteResponseBlock:(SKPaymentTransaction *)transaction {
    //NSLog(@"交易号:%@交易结束",transaction.transactionIdentifier);
     if (transaction.error
         || transaction.transactionState == SKPaymentTransactionStateFailed) {
         NSLog(@"交易号:%@交易失败errorCode:%ld##errorReason:%@",transaction.transactionIdentifier,transaction.error.code,transaction.error.localizedDescription);
         return;
     }
     
     if (transaction.transactionState == SKPaymentTransactionStatePurchased) {
         NSLog(@"交易号:%@交易成功",transaction.transactionIdentifier);
         //建议与App同步数据
         [self requestSuccess:NO];
     }
}

#pragma mark 交易最终结果处理（成功、失败）
- (void)requestSuccess:(BOOL)isChecked
{
    if (isChecked) {
        [LPToast toast:@"支付成功"];
        !self.tradeResultBlock ? : self.tradeResultBlock(YES, 0, nil);
        if (!self.tradeResultBlock) {
            if([self.delegate respondsToSelector:@selector(requestSuccess)])
            {
                [self.delegate requestSuccess];
            }
        }
    }
    self.goodsRequesting = NO;
}

- (void)handleError:(NSInteger)code error:(NSString *)error {
    
    switch (code) {
        case IAP_FILEDCOED_APPLECODE:
        {
            [LPToast toast:error];
            break;
        }
        case IAP_FILEDCOED_NORIGHT:
        {
            [LPToast toast:@"请您开启内购支付"];
            break;
        }
        case IAP_FILEDCOED_EMPTYGOODS:{
            [LPToast toast:@"商品获取出错"];
            break;
        }
        case IAP_FILEDCOED_CANNOTGETINFORMATION:
        {
            [LPToast toast:@"商品获取出错"];
            break;
        }
        case IAP_FILEDCOED_USERCANCEL:
        {
            [LPToast toast:@"您已取消交易"];
            break;
        }
        case IAP_FILEDCOED_BUYING:
        {
            [LPToast toast:@"交易正在进行"];
            break;
        }
        case IAP_FILEDCOED_NOTLOGGEDIN:
        {
            break;
        }
        default:
            [LPToast toast:@"支付失败，请稍后重试"];
            break;
    }
    
    self.goodsRequesting = NO;
    !self.tradeResultBlock ? : self.tradeResultBlock(NO, 0, nil);
    if (!self.tradeResultBlock) {
        if([self.delegate respondsToSelector:@selector(filedWithErrorCode:andError:)])
        {
            [self.delegate filedWithErrorCode:code andError:error];
        }
    }
}

#pragma mark tool
- (void)printProduct:(SKProduct *)product{
    NSLog(@"Price: %@",[self.iap getLocalePrice:product]);
    NSLog(@"Title: %@",product.localizedTitle);
}

@end
